package net.ujacha.bethany.conv;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.DatabaseBuilder;
import com.healthmarketscience.jackcess.Row;
import com.healthmarketscience.jackcess.Table;

public class BethanyMdbConverter {

	private final static Logger LOGGER = LoggerFactory
			.getLogger(BethanyMdbConverter.class);

	private final static String BETHANY_TABLE_NAME = "Table1";

	private final static String FIELD_NAMES[] = { "ID", "주제", "제목", "입력일",
			"그림1", "그림2", "내용" };

	public List<BethanyModel> conv(File mdbFile) throws Exception {

		List<BethanyModel> list = new ArrayList<BethanyModel>();

		LOGGER.info("File Open : {}", mdbFile.getName());

		Database db = null;

		try {

			db = DatabaseBuilder.open(mdbFile);

			Table table = db.getTable(BETHANY_TABLE_NAME);

			if (table != null) {

				for (Row row : table) {
					BethanyModel b = new BethanyModel();

					try {

						b.setId((Integer) row.get(FIELD_NAMES[0]));
						b.setCategory((String) row.get(FIELD_NAMES[1]));
						b.setTitle((String) row.get(FIELD_NAMES[2]));
						b.setWriteDate((Date) row.get(FIELD_NAMES[3]));
						b.setPic1(row.get(FIELD_NAMES[4]));
						b.setPic2(row.get(FIELD_NAMES[5]));
						b.setContent((String) row.get(FIELD_NAMES[6]));

					} catch (Exception e) {
						e.printStackTrace();
						LOGGER.error("{} : {}", b.getId(), e.getMessage());
					}

					//LOGGER.debug(b.toString());
					list.add(b);

				}

			} else {
				throw new IllegalAccessException("not found table : "
						+ BETHANY_TABLE_NAME);
			}

		} catch (Exception e) {

			throw e;

		} finally {

			IOUtils.closeQuietly(db);

		}

		return list;

	}
	
	public static void main(String[] args) {
		
		BethanyMdbConverter converter = new BethanyMdbConverter();
		
		File file = new File("C:/Users/shkim/Desktop/MDB Files 002.mdb");
		try {
			List<BethanyModel> list = converter.conv(file);
			
			for(BethanyModel b : list){
				
				System.out.println(b.toString());
				
			}
				
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}
